package com.mocchira.music.radio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileUtil {
    public static long getDirectoryTotalFileSize(File dir, boolean recursive) {
        long ret = 0;
        if (dir == null || !dir.isDirectory()) return -1;
        File[] list = dir.listFiles();
        for (int i = 0; i < list.length; i++) {
            if (recursive && list[i].isDirectory())
                ret += getDirectoryTotalFileSize(list[i], recursive);
            ret += list[i].length();
        }
        return ret;
    }
    public static boolean deleteAllFiles(File dir, boolean recursive) {
        boolean ret = true;
        if (dir == null || !dir.isDirectory()) return false;
        File[] list = dir.listFiles();
        for (int i = 0; i < list.length; i++) {
            if (list[i].isFile() && list[i].canWrite()) {
                ret = list[i].delete();
                if (!ret) break;
            } else if (list[i].isDirectory() && recursive) {
                deleteAllFiles(list[i], recursive);
            }
        }
        return ret;
    }
    public static String getContents(File src) throws IOException {
        String ret = "";
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF-8"));
        try {
            while ((line = br.readLine()) != null) {
                ret += line;
            }
        } finally {
            if (br != null) br.close();
        }
        return ret;
    }
    public static void putContents(String src, File tmp, File dst) throws IOException {
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmp), "UTF-8"));
        try {
            br.write(src);
            boolean ret = tmp.renameTo(dst);
            if (!ret) 
                throw new IOException("rename failed:from " + tmp.getAbsolutePath() + " to " + dst.getAbsolutePath());
        } finally {
            if (br != null) br.close();
        }
    }
}
